package com.example.crm.interceptor;

import com.example.crm.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    TokenService tokenService;

    /**
     * 目标方法执行之前
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method = request.getMethod();
        log.info(method);
        if (request.getMethod().equals("OPTIONS")) {
            return true;
        } else {
            String token = request.getHeader("token");
            log.info(token);
            if (token == null) {
                return false;
            } else {
                Object object = tokenService.getToken(token);
                if (object != null) {
                    return true;
                }
                return false;
            }
        }

/*
        Map<String, String> cookiesMap = new HashMap<>();
        Cookie[] cookies = request.getCookies();
        if(cookies==null){
            return false;
        }else{
            for (Cookie c : cookies) {
                cookiesMap.put(c.getName(), c.getValue());
            }
            Object object = tokenService.getToken(cookiesMap.get("token"));
            if (object!=null) {
                return true;
            }
            return false;
        }*/

    }

    /**
     * 目标方法执行之后
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 页面渲染之后
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
